#!/bin/ash

type inotifywait >/dev/null || exit 1

home="/home/defaultuser"
dir="$home/.config/hosts-block"

ifmt="inotifywaiting: %w: %e %f"

s_hb() {
    [ "$2" = forced ] && srvc=hosts-block-forced.service || srvc=hosts-block.service
    echo "$1: Starting $srvc"
    systemctl start $srvc
}
wait_for_path() {
    # $1 is just a unique identifier
    # $2 should never have a slash at the end:
    local path="$2"
    [ -r "$path" ] && return 1
    local base="${path%/*}"
    echo "$1: Waiting for existence of ${path##*/} in $base"
    while [ ! -r "$path" ] && [ -d "$base" ]; do
        inotifywait -q --format "$1: $ifmt" -e create "$base"
    done
    [ -r "$path" ] || return 1
}
watch() {
    # $1 is just a unique identifier
    local file="$2"
    while sleep 1; do
        [ -d "$home" ] && [ -r "$home" ] || { echo "$1: Cannot read $home!"; exit 1; }
        wait_for_path $1 "${dir%/*}" # ~/.config
        wait_for_path $1 "$dir"
        wait_for_path $1 "$file" && s_hb $1 $3
        echo "$1: Waiting for modification/deletion of $file"
        inotifywait -q --format "$1: $ifmt" -e modify "$file"; s_hb $1 $3
    done
}

watch whitelist "$dir/whitelist.txt" & p1=$!
watch blacklist "$dir/blacklist.txt" & p2=$!
watch configura "$dir/cfg.sh" forced & p3=$!

# If systemd started this, don't trap anything.
[ -n "$INVOCATION_ID" ] || trap "kill $p1 $p2 $p3" EXIT INT TERM KILL

wait

exit 0
